// pages/user/index.js
const app = getApp();
let api = require('../../utils/api.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userData:{},
    dialogShow: false,
    showOneButtonDialog: false,
    code:'',
    sendTime: '发送验证码',
    sendColor: '#363636',
    snsMsgWait: 60
  },

 

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var token = wx.getStorageSync('TOKEN');
    var that=this;
    that.setData({
      isLogin: token ? true : false,
    })
    if(token){
      app.getUserInfo().then((res)=>{
        var userData = {};
        var userName = '';
        if ( res.nickname != null) {
          userName = res.nickname;
        }
        userData = {
          userName: userName,
          userHead:  res.headImg,
          phone: res.phone,
        }
      app.getRemind()

        that.setData({
          userData: userData
        })

      })
   
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    console.log(res);
    if (res.from === 'button') {
      // console.log('来自页面内转发按钮');
      // wx.switchTab({
      //   url: '/pages/index/index'
      // })
      this.setData({
        showShareModelStatus: false
      })
    } else if (res.from === 'menu') {
      console.log(res.from);
      console.log('右上角菜单转发按钮');
    }
  },
  
  /*
  * 分享应用
   */
  showShareModel:function(e){
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showShareModelStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  //隐藏对话框
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showShareModelStatus: false
      })
    }.bind(this), 200)
  },
// 编辑昵称
  editUserName: function () {
    this.setData({
      nameDialogShow: true,
    })
  },
  // 编辑电话
  editUserPhone:function(){
    this.setData({
      phoneDialogShow: true
    })
  },
  tapDialogButton(e) {
    this.setData({
      phoneDialogShow:false,
      nameDialogShow: false,
      showOneButtonDialog: false
    })
  },
  tapOneDialogButton(e) {
    this.setData({
      showOneButtonDialog: true
    })
  },
  // 输入监听
  inputWacth: function (e) {
   // console.log(e);
    let item = e.currentTarget.dataset.model;
    this.setData({
      [item]: e.detail.value
    });
  },
  // 关闭弹框
  _cancelEvent: function (e) {
   // console.log(e);
    this.setData({
      editNickname:'',
      editPhone:'',
      phoneDialogShow: false,
      nameDialogShow: false,
    });
  },
  // 提交用户名
  _nameConfirmEvent: function (e) {
    var that = this;
    var token = wx.getStorageSync('TOKEN');
    var type = 'nickname';
    var value = that.data.editNickname;
    var search = "^(?:(?=.*[0-9].*)(?=.*[A-Za-z].*)(?=.*[\\W].*))[\\W0-9A-Za-z]{8,16}$";
    var reg = /^[\u4e00-\u9fa5]+$/;//只要包含中文
    if (!reg.test(value)) {
     // console.log(value);
     // console.log(reg.test(value));
      wx.showToast({
        title: '真实姓名，暂不支持字母、数字及符号，请重新输入',
        icon: 'none'
      })
      return;
    }
    var params = {
      dataname: 'userData.userName',
      storageName: 'NICKNAME'
    }
    that.changeUserInfo(type, value, token, params);
  },

  // 提交手机
  _phoneConfirmEvent: function (e) {
    var that = this;
    var token = wx.getStorageSync('TOKEN');
    var type = 'phone';
    var value = that.data.editPhone;

    var code = that.data.code;
    if (value == "") {
      that.toast("手机号不可为空");
      return;
    }
    if (code == "") {
      that.toast("验证码不可为空");
      return;
    }
    var params = {
      dataname: 'userData.phone',
      storageName: 'PHONE'
    }
    that.changeUserInfo(type, value, token, params,code);
  },

  // 修改用户操作
  changeUserInfo: function (type, value, token, params,code) {
    var that = this;
    var param = {
      [type]: value,
    }
    if(code){
      param.verifyCode=code
    }
    api._put('/user/info/edit', param, token).then(res => {
      if (res.code == 200) {
        if (params.imgUrl) {
          value = params.imgUrl
        }
        var item = params.dataname;
        var storageName = params.storage
        that._cancelEvent();
        that.setData({
          [item]: value
        });
        wx.setStorageSync(storageName, value);
      }else if (res.code == 20000013 || res.code == 20000014){
        wx.showToast({
          title: res.message,
          icon: 'none',
        })
      }
       else {
        wx.showToast({
          title: '网络忙，请稍后重试',
          icon: 'none',
        })
      }
    })
  },
  /**
   * 修改头像
   */
  changeAvatar: function (e) {
    var _this = this;
    var token = wx.getStorageSync('TOKEN');
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        //这里是上传操作
        wx.uploadFile({
          url: 'https://www.gdhtc.cn/api/file/img/upload', //里面填写你的上传图片服务器API接口的路径 
          filePath: tempFilePaths[0], //要上传文件资源的路径 String类型 
          name: 'file', //按个人情况修改，文件对应的 key,开发者在服务器端通过这个 key 可以获取到文件二进制内容，(后台接口规定的关于图片的请求参数)
          header: {
            "Content-Type": "multipart/form-data", //记得设置
            //和服务器约定的token, 一般也可以放在header中
            'token': token
          },

          success: function (res) {
            //当调用uploadFile成功之后，再次调用后台修改的操作，这样才真正做了修改头像
            if (res.statusCode = 200) {
              var data = JSON.parse(res.data);
              // var statusCode = res.statusCode
             // console.log("返回值1" + data);
              var type = 'headImg';
              var value = data.result.id;
              var params = {
                dataname: 'userData.userHead',
                storageName: 'HEADIMG',
                imgUrl: data.result.thumbUrl
              }
              _this.changeUserInfo(type, value, token, params);
              //// console.log("返回值2" + statusCode)
              //这里调用后台的修改操作， tempFilePaths[0],是上面uploadFile上传成功，然后赋值到修改这里。
            }
          }
        })
      }
    })
  },

  // 获取验证码
  sendCode: function () {
    var that = this;

    if (that.data.editPhone == "") {
      that.toast('请输入手机号');
      return;
    }else if (!(/^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(that.data.editPhone))) {
      that.toast('手机号输入错误');
      return;
    }else{
      api._get('/sms/send/'+that.data.editPhone+'/1', '', '').then(res => {
       // console.log(res)
        if(res.code==200){
         
        }else{
          wx.showToast({
            title: '请稍后重试',
            icon: 'none',
          })
        }
      })
    // 60秒后重新获取验证码
    var inter = setInterval(function () {
      that.setData({
        smsFlag: true,
        sendColor: '#cccccc',
        sendTime: that.data.snsMsgWait + 's后重发',
        snsMsgWait: that.data.snsMsgWait - 1
      });
      if (that.data.snsMsgWait < 0) {
        clearInterval(inter)
        that.setData({
          sendColor: '#363636',
          sendTime: '发送验证码',
          snsMsgWait: 60,
          smsFlag: false
        });
      }
    }.bind(that), 1000);
    }


  },

  inputCode: function (e) {
    this.setData({
      code: e.detail.value
    })
  },
  // toast方法抽取
  toast: function (msg) {
    wx.showToast({
      title: msg,
      icon: 'none',
      duration: 2000,
      mask: true
    })
  },
  login(){
    app.goAuthpPages()
  },
  
  callExpert: function (e) {
    //// console.log(e.currentTarget.dataset.phone)
    var phone = e.currentTarget.dataset.phone;
    app.callExpert(phone);
  },
})